Creating Logical Backups Using mysqldump in MySQL
Course: MySQL Training Course
Topic: Creating Logical Backups Using mysqldump
Course Link: MySQL Training Course – JustAcademy
Demo Link: Register for a Course Demo
Official Documentation: MySQL mysqldump Documentation
1. Introduction to Logical Backups
Database backup is an important activity in MySQL database administration. It involves creating a copy of database information so that the data can be recovered if the original database is accidentally deleted, corrupted, damaged, or becomes unavailable.
MySQL provides a command-line utility called mysqldump for creating logical backups. It reads database structures and data from a MySQL server and generates output that can be used to recreate database objects and restore their contents.
A logical backup is commonly stored in a file with the .sql extension. The file may contain SQL statements such as CREATE TABLE, INSERT INTO, and other statements required to rebuild the exported database objects.
Example
mysqldump -u root -p company_db > company_db_backup.sql
This command exports the company_db database into the file company_db_backup.sql. The -u root option specifies the MySQL username, and -p prompts for the password.
2. Learning Objectives
After completing this topic, you will be able to:
- Understand logical backups and their importance.
- Explain the purpose and working of
mysqldump.
- Create logical backups of individual databases and selected tables.
- Back up multiple databases using a single command.
- Understand common backup options and their uses.
- Create schema-only and data-only backups.
- Include stored procedures, functions, triggers, and scheduled events when required.
- Restore SQL dump files using the MySQL command-line client.
- Verify backup files and troubleshoot common errors.
- Develop a basic database backup and recovery strategy.
3. What Is a Logical Backup?
A logical backup stores database information in a logical representation rather than copying the underlying database files directly. It contains definitions of database objects and, when requested, the data stored in tables.
For example, a logical backup of an employee database can contain the statements required to create the employees table and insert its records.
Example of SQL Statements in a Backup
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10,2)
);
INSERT INTO employees
(employee_id, employee_name, department, salary)
VALUES
(1, 'Amit Sharma', 'IT', 55000.00),
(2, 'Priya Patel', 'HR', 48000.00);
This is a simplified example of the type of SQL that a logical dump may contain. A real dump can include additional table options, indexes, constraints, comments, session settings, and statements for other database objects.
Characteristics of Logical Backups
- Represent database structures and data in a logical format.
- Can be stored as readable SQL text.
- Can be restored using a compatible MySQL client and server.
- Can be used to migrate databases between compatible environments.
- Can support selective exports of databases, tables, or rows.
- May require considerable time and storage for very large databases.
4. What Is mysqldump?
mysqldump is a MySQL command-line utility used to export one or more databases. It produces SQL statements that can recreate database objects and restore their data. It also supports other output formats, including delimited text and XML.
Database administrators commonly use it for routine backups, database migration, development environments, testing, and recovery preparation.
Basic Syntax
mysqldump [options] database_name [table_name ...] > backup_file.sql
| Component |
Description |
mysqldump |
Starts the MySQL logical export utility. |
-u username |
Specifies the MySQL account. |
-p |
Prompts for the account password. |
database_name |
Specifies the database to export. |
table_name |
Optionally specifies a table to export. |
> |
Redirects command output to a file in the operating-system shell. |
backup_file.sql |
Specifies the output file that stores the dump. |
5. Why Are Logical Backups Important?
5.1 Data Protection
Backups help recover information after accidental deletion, application errors, hardware failures, or other incidents that affect database availability or integrity.
5.2 Database Migration
A logical backup can be transferred to another compatible MySQL environment and imported there. This is useful when moving databases between development, testing, and production servers.
5.3 Application Testing
Developers can restore a backup into a test environment to reproduce application issues or test new features without directly changing the production database.
5.4 Disaster Recovery
A verified backup provides a recovery source if the original database becomes unavailable or must be rebuilt.
5.5 Data Inspection
SQL dump files can be inspected with a text editor or command-line tools to review exported statements and understand database structures.
6. Logical Backup vs. Physical Backup
| Feature |
Logical Backup |
Physical Backup |
| Representation |
SQL statements or logical data exports |
Database files and physical storage data |
| Typical method |
mysqldump |
Physical backup utilities or storage snapshots |
| Readability |
SQL output can generally be read as text |
Files are not usually directly readable as SQL |
| Portability |
Often suitable for compatible systems and versions |
More dependent on storage format and server configuration |
| Selective export |
Can export selected databases, tables, or rows |
Typically works at the physical storage level |
| Large databases |
Export and import may take longer |
Can provide faster recovery when appropriately configured |
| Typical use |
Migration, selective recovery, and data transfer |
Large-scale database recovery and instance restoration |
Logical and physical backups serve different purposes. Production environments may use both methods to meet recovery requirements.
7. Preparing to Use mysqldump
7.1 Check Whether mysqldump Is Installed
Open Command Prompt or PowerShell on Windows, or a terminal on Linux or macOS, and execute:
mysqldump --version
If the command is not recognized, verify that the MySQL client tools are installed and that the directory containing mysqldump is included in the system PATH.
7.2 Connect to MySQL
mysql -u root -p
After connecting, list the available databases:
SHOW DATABASES;
SQL statements such as SHOW DATABASES; are executed inside the MySQL client, not directly in the operating-system terminal.
7.3 Check Database Permissions
The account used for a backup must have sufficient privileges for the objects and options being exported. Depending on the MySQL version and command options, these can include:
SELECT for reading table data.
SHOW VIEW for exporting views.
TRIGGER for exporting triggers.
LOCK TABLES when the selected backup behavior requires table locking.
- Additional privileges for specific options, routines, events, or server settings.
Use a dedicated backup account with the minimum required privileges instead of automatically using a highly privileged administrator account.
8. Creating a Backup of a Single Database
To export a database into a SQL file, run the following command from your operating-system terminal:
mysqldump -u root -p company_db > company_db_backup.sql
Command Explanation
mysqldump starts the export process.
-u root specifies the MySQL username.
-p prompts for the password.
company_db identifies the database to export.
> redirects the output to a file.
company_db_backup.sql is the resulting backup file.
The output file is created relative to the current shell directory unless an absolute path is specified. An existing file with the same name may be overwritten, so select the destination carefully.
Using an Absolute Path
Windows example:
mysqldump -u root -p company_db > "C:\MySQLBackups\company_db_backup.sql"
Linux example:
mysqldump -u root -p company_db > /var/backups/mysql/company_db_backup.sql
Ensure the destination directory exists and that the operating-system account has permission to write to it.
9. Creating a Backup of Multiple Databases
The --databases option allows multiple named databases to be exported into one file. The dump normally includes statements to create and select the specified databases.
Example
mysqldump -u root -p --databases company_db sales_db inventory_db > selected_databases_backup.sql
This command exports the three named databases into a single SQL file.
Backing Up All Databases
mysqldump -u root -p --all-databases > all_databases_backup.sql
This requests a dump of all databases supported by the utility and accessible to the account. It does not automatically capture every aspect of a MySQL installation, such as configuration files and all server-level settings.
10. Backing Up a Specific Table
You can export an individual table instead of a complete database. This can be useful before changing a table or when transferring a limited dataset.
Example
mysqldump -u root -p company_db employees > employees_backup.sql
This exports the employees table from company_db.
Backing Up Multiple Tables
mysqldump -u root -p company_db employees departments salaries > selected_tables_backup.sql
When restoring table-level backups, consider dependencies such as foreign keys, related tables, views, and triggers. A selected-table dump may not be sufficient to rebuild an entire application database.
11. Important mysqldump Options
| Option |
Purpose |
Example |
--databases |
Exports one or more named databases. |
--databases company_db sales_db |
--all-databases |
Requests a dump of all databases. |
--all-databases |
--single-transaction |
Creates a consistent transactional snapshot for suitable transactional tables. |
--single-transaction |
--quick |
Reads rows incrementally instead of buffering an entire table in client memory. |
--quick |
--routines |
Includes stored procedures and functions. |
--routines |
--events |
Includes scheduled events. |
--events |
--triggers |
Includes table triggers; enabled by default in supported versions unless disabled. |
--triggers |
--no-data |
Exports table definitions without table rows. |
--no-data |
--no-create-info |
Exports data without table creation statements. |
--no-create-info |
--where |
Exports rows matching a condition for a specified table. |
--where="employee_id > 100" |
--ignore-table |
Excludes a specified table from the dump. |
--ignore-table=company_db.audit_logs |
12. Using --single-transaction for Consistent Backups
In a live database, data may change while a backup is running. The backup strategy must account for those changes to avoid capturing inconsistent data.
The --single-transaction option starts a transaction that provides a consistent snapshot for transactional tables such as InnoDB. It is often useful when the database must remain available while the export runs.
Example
mysqldump -u backup_user -p --single-transaction company_db > company_db_consistent_backup.sql
Important Considerations
- The consistent-snapshot behavior applies to transactional storage engines such as InnoDB.
- Nontransactional tables are not guaranteed to remain consistent under this option.
- Avoid schema-changing operations such as
ALTER TABLE, DROP TABLE, RENAME TABLE, and TRUNCATE TABLE on dumped tables while the backup is running.
--single-transaction and --lock-tables are mutually exclusive.
- Depending on server settings, GTID configuration can introduce additional privilege or compatibility considerations.
For suitable InnoDB databases, combining --single-transaction and --quick is a common approach.
13. Including Stored Procedures, Functions, Triggers, and Events
A database may contain more than tables and records. It can also include views, triggers, stored procedures, stored functions, and scheduled events. Review these objects before choosing the required backup options.
Example Command
mysqldump -u backup_user -p --single-transaction --quick --routines --events --triggers company_db > company_db_full_logical_backup.sql
| Object |
Relevant Option |
Explanation |
| Tables and rows |
Default dump behavior |
Exports table definitions and data unless excluded by options. |
| Views |
Default object handling |
Check privileges and dependencies. |
| Triggers |
--triggers |
Included by default in supported versions unless disabled. |
| Stored procedures and functions |
--routines |
Requests stored routine definitions. |
| Scheduled events |
--events |
Requests Event Scheduler event definitions. |
For current option details and privilege requirements, refer to the official mysqldump reference.
14. Creating a Schema-Only Backup
A schema-only backup contains database structure without ordinary table row data. It can be useful when preparing a development environment or reviewing table definitions.
Command
mysqldump -u root -p --no-data company_db > company_db_schema.sql
The resulting dump contains structural definitions for the included objects, but it does not include ordinary table rows.
15. Creating a Data-Only Backup
A data-only backup omits table creation statements. It is useful when the target database already contains compatible table definitions.
Command
mysqldump -u root -p --no-create-info company_db > company_db_data_only.sql
Before restoring a data-only dump, verify that the target schema is compatible with the exported data. Column definitions, constraints, data types, and existing records can affect the result.
16. Backing Up Selected Rows
The --where option allows you to export only rows that match a condition for a specified table.
Example
mysqldump -u root -p company_db employees --where="department = 'IT'" > it_employees_backup.sql
This command exports rows from the employees table where the department is IT. The table definition is also included unless other options change that behavior.
A filtered dump is not a complete database backup. Related records in other tables may be required to preserve relationships and application behavior.
17. Restoring a Logical Backup
Creating a backup is only part of the process. You should also test that the backup can be restored successfully.
17.1 Restore a Single-Database Dump
If the dump was created without the --databases option, create or select the destination database before importing it.
mysql -u root -p -e "CREATE DATABASE company_restore;"
mysql -u root -p company_restore < company_db_backup.sql
This example assumes the dump does not contain statements that select or create a conflicting database. Review the dump and adjust the destination procedure when necessary.
17.2 Restore a Dump Created with --databases
A dump created with --databases usually includes statements to create and select the named databases.
mysql -u root -p < selected_databases_backup.sql
Check the file before importing it if you need to change database names or avoid replacing existing objects.
17.3 Restore a Table-Level Dump
mysql -u root -p company_restore < employees_backup.sql
Confirm that the target database exists and that the table definitions and dependencies will not conflict with existing objects.
18. Verifying a Backup
A command that appears to finish successfully does not prove that a backup is usable. Verification should be part of the backup workflow.
Verification Steps
- Check the command's exit status.
- Confirm that the output file exists and has a plausible size.
- Inspect the beginning and end of the SQL file for expected statements and signs of an incomplete export.
- Review the logs for errors and warnings.
- Restore the backup into an isolated test database or test server.
- Compare expected table counts and selected records with the source.
- Verify important views, triggers, routines, events, indexes, and constraints.
- Record the restoration time and any manual recovery steps.
A non-empty SQL file is only a basic check. A successful restore test provides stronger evidence that the backup is usable.
19. Creating Timestamped Backup Files
Adding a date and time to the filename helps distinguish backup versions and makes retention management easier.
Linux Example
mysqldump -u backup_user -p --single-transaction --quick --routines --events company_db > "company_db_$(date +%Y-%m-%d_%H-%M-%S).sql"
Windows PowerShell Example
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
mysqldump -u backup_user -p --single-transaction --quick --routines --events company_db > "C:\MySQLBackups\company_db_$timestamp.sql"
Ensure the backup directory exists and that the account running the command can write to it.
20. Automating Logical Backups
Automation makes backups repeatable and reduces reliance on manual execution. A production workflow should include logging, failure detection, retention management, monitoring, and recovery testing.
Example Linux Backup Script
#!/bin/bash
set -o pipefail
BACKUP_DIR="/var/backups/mysql"
DB_NAME="company_db"
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_${TIMESTAMP}.sql"
LOG_FILE="$BACKUP_DIR/backup.log"
mkdir -p "$BACKUP_DIR"
if mysqldump --defaults-extra-file=/etc/mysql/backup.cnf \
--single-transaction --quick --routines --events \
"$DB_NAME" > "$BACKUP_FILE" 2>> "$LOG_FILE"; then
if [ -s "$BACKUP_FILE" ]; then
echo "$(date): Backup completed: $BACKUP_FILE" >> "$LOG_FILE"
else
echo "$(date): Backup file is empty: $BACKUP_FILE" >> "$LOG_FILE"
exit 1
fi
else
echo "$(date): Backup failed for $DB_NAME" >> "$LOG_FILE"
rm -f "$BACKUP_FILE"
exit 1
fi
Important: This example assumes that /etc/mysql/backup.cnf has been created with suitable connection settings and secure permissions. Test the script in your environment before using it in production. A non-empty file alone does not establish that a backup can be restored.
Scheduling with Cron
On Linux, a cron entry can schedule the script to run daily at 2:00 AM:
0 2 * * * /usr/local/bin/mysql_backup.sh
Choose a schedule according to business requirements, database activity, backup duration, and acceptable data loss. Monitor scheduled jobs and configure alerts for failures.
21. Securing Backup Files and Credentials
Backup files may contain confidential information, including customer records, employee information, financial details, and application data. Protect the backup files and the credentials used to create them.
- Avoid placing passwords directly in command-line arguments or scripts.
- Use a securely protected MySQL option file or another supported credential-management method for automated authentication.
- Restrict operating-system permissions on backup files and credential files.
- Encrypt sensitive backup files and use secure channels when transferring them.
- Keep an additional copy on separate storage away from the production server.
- Define a retention policy and securely dispose of expired backup copies.
- Use a dedicated backup account with the minimum required privileges.
- Keep encryption keys accessible to authorized recovery personnel through a documented process.
22. Common mysqldump Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
mysqldump is not recognized |
Client tools are missing or the installation directory is not in PATH. |
Install or locate the MySQL client utilities and configure PATH. |
Access denied |
Incorrect credentials or insufficient privileges. |
Check the account, password, host, and required privileges. |
Unknown database |
The database name is incorrect or unavailable on the selected server. |
Verify the database name and connection target. |
Permission denied |
The operating-system account cannot write to the output directory. |
Choose a permitted directory and verify its permissions. |
| Backup file is empty or incomplete |
The command failed, was interrupted, or output handling was incorrect. |
Check the exit status and logs, then rerun the backup and test it. |
| Stored procedures or events are missing |
The required options were not included. |
Use --routines and/or --events and check privileges. |
| Restore fails because an object exists |
The destination contains conflicting objects or records. |
Use a clean test database or plan the replacement process carefully. |
| Backup takes too long |
Large tables, limited resources, network latency, or storage bottlenecks. |
Consider --quick and whether another backup method is more suitable. |
| Nontransactional data is inconsistent |
--single-transaction does not guarantee a consistent snapshot for nontransactional tables. |
Plan appropriate locking or another backup strategy for those tables. |
23. Best Practices for Logical Backups
- Define a backup schedule based on recovery-point and recovery-time requirements.
- Use
--single-transaction for suitable InnoDB workloads when a consistent snapshot is needed.
- Consider
--quick for large tables to reduce client-side buffering.
- Include routines and events explicitly when they are part of the application.
- Verify that required views, triggers, indexes, and constraints are included.
- Store backup copies separately from the production database server.
- Protect backup files with encryption and access controls.
- Monitor automated backup jobs and investigate failures.
- Keep multiple backup generations according to a documented retention policy.
- Perform regular restoration tests in a safe environment.
- Check compatibility between source and target MySQL versions.
- Document backup commands, permissions, dependencies, and recovery procedures.
- Never rely solely on a successful export message without testing recovery.
24. Practical Example: Backing Up an Employee Database
Assume an organization has a database called company_db containing tables such as employees, departments, and salaries. The database must be backed up before an application update.
Step 1: Inspect the Database
mysql -u root -p
SHOW DATABASES;
USE company_db;
SHOW TABLES;
SELECT COUNT(*) FROM employees;
Step 2: Create the Backup Directory
On Linux, create a directory with restricted access:
sudo mkdir -p /var/backups/mysql
sudo chmod 700 /var/backups/mysql
Step 3: Create the Backup
mysqldump -u backup_user -p --single-transaction --quick --routines --events company_db > /var/backups/mysql/company_db_before_update.sql
Step 4: Inspect the Result
Check the command's exit status, review any warnings or errors, and inspect the output file. Record the date, time, database name, and result of the backup operation.
Step 5: Restore into a Test Database
mysql -u root -p -e "CREATE DATABASE company_db_test;"
mysql -u root -p company_db_test < /var/backups/mysql/company_db_before_update.sql
If the dump includes database-selection statements or assumes the original database name, adjust the restoration procedure accordingly. Do not test restoration by overwriting the production database.
Step 6: Validate the Restored Database
USE company_db_test;
SHOW TABLES;
SELECT COUNT(*) FROM employees;
SELECT * FROM employees LIMIT 5;
Compare the restored data with the expected source state and verify important database objects. Document the results before relying on the backup for recovery.
25. Hands-On Exercises
- Create a logical backup of a database named
student_db.
- Export two databases into a single SQL file.
- Export only the
employees table from company_db.
- Create a schema-only dump using
--no-data.
- Create a data-only dump using
--no-create-info.
- Back up an InnoDB database using
--single-transaction and --quick.
- Include stored procedures and scheduled events in a backup.
- Restore a dump into a separate test database.
- Compare table counts and selected records after restoration.
- Create a scheduled backup script that logs errors and generates timestamped files.
26. Mini Project: Database Backup and Recovery Plan
Project Objective: Create a repeatable logical backup and restore workflow for a sample MySQL database.
Project Requirements
- Create or select a sample database with multiple tables.
- Document its name, approximate size, and important objects.
- Choose a backup account with appropriate minimum privileges.
- Generate timestamped SQL backup files.
- Include routines and events when the database uses them.
- Record command output and failures in a log.
- Restore a backup into a separate database.
- Compare table counts and validate important objects.
- Document file security, retention rules, and recovery steps.
Expected Outcome
The completed project should demonstrate logical backup creation, basic validation, test restoration, and a documented recovery process.
27. Interview Questions and Answers
Q1. What is a logical backup in MySQL?
Answer: A logical backup represents database structure and data in a logical format, commonly as SQL statements that can recreate objects and restore records.
Q2. What is mysqldump?
Answer: mysqldump is a command-line utility that exports MySQL databases, tables, and related definitions into a dump file or another supported output format.
Q3. How do you back up one database?
Answer: Use mysqldump -u username -p database_name > backup.sql, replacing the example names with the required values.
Q4. How do you back up all databases?
Answer: Use mysqldump -u username -p --all-databases > all_databases.sql with an account that has the required privileges.
Q5. What does --single-transaction do?
Answer: It creates a consistent transactional snapshot for suitable transactional tables such as InnoDB. It does not guarantee consistency for nontransactional tables.
Q6. Why is --quick useful?
Answer: It retrieves table rows incrementally rather than buffering the entire result in client memory.
Q7. How do you include stored procedures and functions?
Answer: Use the --routines option.
Q8. How do you include scheduled events?
Answer: Use --events and ensure the account has the necessary privileges.
Q9. Are triggers included by default?
Answer: Triggers are included by default in supported versions unless trigger dumping is disabled. The account must have the required privileges.
Q10. How do you create a schema-only backup?
Answer: Use --no-data to export table definitions without ordinary table rows.
Q11. How do you create a data-only backup?
Answer: Use --no-create-info to omit table creation statements.
Q12. How do you restore a SQL dump?
Answer: Use the MySQL client with input redirection, such as mysql -u username -p target_db < backup.sql. The exact command depends on whether the dump contains database-selection statements.
Q13. What is the difference between logical and physical backups?
Answer: Logical backups export database definitions and data in a logical format, whereas physical backups copy database files or other physical storage representations.
Q14. Why should backups be restored for testing?
Answer: Restore tests verify that the dump is usable, important objects are present, and the recovery procedure works as expected.
Q15. How should backup files be secured?
Answer: Restrict access, protect credentials, encrypt sensitive copies, transfer files securely, and follow a documented retention policy.
28. Quick Revision Checklist
- Logical backup: Exports database objects and data in logical form.
- Utility:
mysqldump.
- Single database:
mysqldump -u user -p db_name > backup.sql.
- Multiple databases: Use
--databases.
- All databases: Use
--all-databases.
- Consistent InnoDB snapshot: Consider
--single-transaction.
- Large table exports: Consider
--quick.
- Stored procedures and functions: Use
--routines.
- Scheduled events: Use
--events.
- Schema only: Use
--no-data.
- Data only: Use
--no-create-info.
- Restore: Use the
mysql client with the appropriate target database.
- Verification: Check logs, inspect the dump, and test restoration.
- Security: Protect credentials and backup files.
29. Conclusion
Creating logical backups with mysqldump is a fundamental MySQL administration skill. It allows database administrators and developers to export database definitions and data, move information between compatible environments, and prepare for recovery after data loss or application problems.
A reliable backup process requires more than running a command. You must choose appropriate options, verify permissions, consider transaction consistency, include required database objects, protect backup files, monitor scheduled jobs, and regularly test restoration in a safe environment.
To learn more, visit the JustAcademy MySQL Training Course or register for a course demo.